﻿using Microsoft.EntityFrameworkCore;
using TuLing.Blazor.Dto;
using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class SupplierService :BaseService
    {
        public SupplierService(DefaultDbContext context) : base(context) { }

        public IEnumerable<Supplier> SearchSupplier()
        {
            return _context.Suppliers.AsNoTracking().ToList();
        }

        public void SaveSupplier(Supplier input)
        {
            var has = _context.Suppliers.Any(m=>m.Name.Equals(input.Name) && m.Id != input.Id);
            if (has)
            {
                throw new Exception("名称已存在，请检查");
            }

            if (input.Id > 0)
            {
                _context.Suppliers.Update(input);
                _context.SaveChanges();
            }
            else {
                _context.Suppliers.Add(input);
                _context.SaveChanges();
                _context.SupplierLogs.Add(new SupplierPayLog
                    {
                        SupplierId = input.Id,
                        CreatedAt = DateTime.Now.Date,
                        Remark="期初账目"
                    });
            }            
        }

        /// <summary>
        /// 获取 
        /// </summary>  
        public Supplier? GetSupplier(long id)
        {
             return _context.Suppliers.FirstOrDefault(s=>s.Id == id);
        }

        /// <summary>
        /// 删除 
        /// </summary>  
        public void DeleteSupplier(long id)
        {
            var s = _context.Suppliers.FirstOrDefault(m => m.Id == id);
            if (s == null)
            {
                throw new Exception("供应商不存在");
            }
            _context.Suppliers.Remove(s);
        }

        /// <summary>
        /// 客户账目明细
        /// </summary> 
        public List<SupplierPayLog> SearchSupplierPayLog(BaseInput input)
        {
            var list = _context.SupplierLogs.AsEnumerable().Where(m => m.SupplierId == input.supplierid);
            return list.ToList();
        }

        /// <summary>
        /// 新增一条账目明细
        /// </summary> 
        public void AddSupplierPayLog(SupplierPayLog input)
        {
            var supplier = _context.Suppliers.FirstOrDefault(s => s.Id == input.SupplierId);
            _context.SupplierLogs.Add(input);
            _context.SaveChanges();
        }

    }
}
